package com.htdata.iiot.api.tsdb.utils;

import java.util.Iterator;
import java.util.Properties;

import org.hbase.async.HBaseClient;

import com.htdata.iiot.api.tsdb.config.Configs;
import com.htiiot.common.config.IConfigManager;

import net.opentsdb.core.TSDB;
import net.opentsdb.utils.Config;

/**
 * TSDB wrapper
 * 
 * @author shanyou
 *
 */
public class TSDBBuilder {
	private Config config;
	private Properties clientConfig;

	public TSDBBuilder(IConfigManager conf, String tsdbConfName) {
		Properties props = conf.config(tsdbConfName).getAll();
		clientConfig = conf.config(Configs.TSDBConfig.CLIENT_CONFIG_SECTION).getAll();
		this.config = new Config(props);
	}

	public TSDBBuilder(IConfigManager conf) {
		this(conf, Configs.TSDBConfig.CONFIG_SECTION);
	}

	public TSDB createTSDB() {
		HBaseClient client = createHBaseClient();
		TSDB tsdb;
		if (client != null) {
			tsdb = new TSDB(client, this.config);
		} else {
			tsdb = new TSDB(this.config);
		}
		return tsdb;
	}

	public HBaseClient createHBaseClient() {
		org.hbase.async.Config async_config = new org.hbase.async.Config();
		Iterator<Object> iter = clientConfig.keySet().iterator();
		if (!iter.hasNext())
			return null;
		while (iter.hasNext()) {
			String key = String.valueOf(iter.next());
			async_config.overrideConfig(key, String.valueOf(clientConfig.get(key)));
		}

		return new HBaseClient(async_config);
	}

	public Config getConfig() {
		return config;
	}

	public TSDBBuilder setConfig(Config config) {
		this.config = config;
		return this;
	}
}
